package arbor.mining.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * UtilItem is the fundamental class for my common utilities.
 * Currently, each utility should contain a logger.
 * Please override getInitProperty() to put the default property for the utility.
 * @author doug
 *
 */
public abstract class UtilItem {	
	private static Logger DEFAULT_LOGGER =  loadDefaultLogger() ;
	protected Logger logger = null;
	protected Properties prop = null;
    protected UtilItem() {
    	/*without specified a new logger, use the default logger*/
       logger = DEFAULT_LOGGER;
       prop = getInitProperty();
    }
    /**
     * When you need to have a new logger, please use loadCustomLogger().
     * @param myLogger
     */
    protected UtilItem(Logger myLogger) {
    	logger = myLogger;
    	prop = getInitProperty();
    }    
    /**
     * To support that if the users don't want to use the default properties.
     * @param myProp
     */
    protected UtilItem(Properties myProp) {
    	logger = DEFAULT_LOGGER;
    	prop = myProp;
    }
    protected UtilItem(Logger myLogger, Properties myProp) {
    	logger = myLogger;
    	prop = myProp;
    }
    /**
     * Load a custom logger. You can use the function before you create a new utility.
     * @param path
     * @return
     */
    public static Logger loadCustomLogger(String path) {
	    Properties logp = new Properties();
	    try {
	      logp.load(new FileInputStream(path));
	    } catch (IOException e) {
	      e.printStackTrace();
	    }	    
	    PropertyConfigurator.configure(logp);
	    
	    return Logger.getRootLogger();	   
    	
    }
    private static Logger loadDefaultLogger() {
	    Properties logp = new Properties();
	    try {
	      logp.load(UtilItem.class.getClassLoader()
	        .getResourceAsStream( "arbor/mining/util/j4util.properties"));
	    } catch (IOException e) {
	      e.printStackTrace();
	    }	    
	    PropertyConfigurator.configure(logp);
	    
	    return Logger.getRootLogger();	   
  }

   /**
   * obtain the initial property for the task.
   * @return
   */
  public abstract Properties getInitProperty();
  
}
